const Config = require("./config.js");
const MongoClient = require("mongodb").MongoClient;
const ObjectID = require('mongodb').ObjectID;

class DB {
  //用于实现单例模式
  static getInstance() {
    if (!DB.instance) {
      DB.instance = new DB();
    }
    return DB.instance;
  }
  //构造方法
  constructor() {
    this.dbClient = ""; //用于存储数据库对象
    this.connect(); //实例化的时候就连接数据库
  }
/* 连接数据库 */
  connect() {
    let that = this;
    return new Promise((resolve, reject) => {
      if (!that.dbClient) {
        //防止数据库连接多次
        MongoClient.connect(
          Config.dbUrl,
          { useUnifiedTopology: true },
          (error, client) => {
            if (error) {
              reject(error);
              return;
            }
            that.dbClient = client.db(Config.dbName); //数据库对象
            resolve(that.dbClient);
          }
        );
      } else {
        resolve(that.dbClient);
      }
    });
  }
/* 查询数据库 带分页 */
  find(collectionName, json1={}, json2={}, pageSize=100, pageNum=1, sortJson={}) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        let result = db.collection(collectionName).find(json1, json2).skip(parseInt(pageSize*(pageNum-1))).limit(pageSize).sort(sortJson);
        result.toArray((error, docs) => {
          if (error) {
            reject(error);
            return;
          } else {
            resolve(docs);
          }
        });
      });
    });
  }
/* 增加数据 */
  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).insertOne(json, (error, result) => {
          if (error) {
            reject(error);
            return;
          }
          resolve(result);
        });
      });
    });
  }
/* 删除数据 */
  delate(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).remove(json, (error, result) => {
          if (error) {
            reject(error);
            return;
          }
          resolve(result);
        });
      });
    });
  }
/* 更新数据 */
  update(collectionName, oldjson, newjson) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).updateOne(
          oldjson,
          {$set:newjson},
          (error, result) => {
            if (error) {
              reject(error);
              return;
            }
            resolve(result);
          }
        );
      });
    });
  }

/* 获取数据_id */
  getObjectId(id){
    return new ObjectID(id);
  }

/* 查询数据总条数 */
  count(collectionName, json){
    return new Promise(resolve => {
      this.connect().then(db => {
        let res = db.collection(collectionName).count(json)
        resolve(res)
      })
    })
  }
}

//导出数据库实例
module.exports = DB.getInstance();